import { FormModal } from "@/components/modal/form.modal"
import { Field_Search } from "@/components/utils/field.list"
import orderService from "@/services/order.service"
import { StoreContext } from "@/store"
import { AsyncModal, OperateRender, IndexRender, FormRender, ListTable, DateRender } from "@whzhuke/antd"
import { useMobx } from "@whzhuke/mobx"
import { Button, Col, Modal, Row, Space } from "antd"
import { useForm } from "antd/es/form/Form"
import React, { useCallback, useContext, useMemo } from "react"
import { EditOrders } from "@/components/form/orders/edit.orders"
import { functionCommon } from "@whzhuke/common"
// const orderTestData = [
//   {
//     id: 1,
//     orderNo: "ORD20240201",
//     goodsName: "铝型材",
//     owner: "宁波某有限公司",
//     deliveryDate: "2024-02-01",
//     contractFile: "铝型材采购合同.pdf",
//     updatedBy: "张三",
//     updateTs: "2024-01-28 11:23:00",
//     createTs: "2024-01-25 09:12:00"
//   },
//   {
//     id: 2,
//     orderNo: "ORD20240208",
//     goodsName: "汽车配件",
//     owner: "上海汽配商贸",
//     deliveryDate: "2024-02-10",
//     contractFile: "汽配销售合同.pdf",
//     updatedBy: "李四",
//     updateTs: "2024-02-02 16:45:00",
//     createTs: "2024-01-30 14:30:00"
//   },
//   {
//     id: 3,
//     orderNo: "ORD20240215",
//     goodsName: "电子元器件",
//     owner: "深圳科技公司",
//     deliveryDate: "2024-02-18",
//     contractFile: "电子元件供货协议.pdf",
//     updatedBy: "王五",
//     updateTs: "2024-02-05 10:20:00",
//     createTs: "2024-02-01 08:50:00"
//   }
// ]

const Page = useMobx(() => {
  const [form] = useForm()
  const { ListStore, UserStore } = useContext(StoreContext)
  const userRole = UserStore.user?.role
  const resolvedRole = useMemo(() => {
    if (userRole && typeof userRole === "string" && userRole.trim()) {
      return userRole.trim().toUpperCase()
    }
    return "ADMIN"
  }, [userRole])
  const orderListService = useMemo(() => {
    return resolvedRole === "ADMIN" ? orderService.allOrderList : orderService.myselfOrderList
  }, [resolvedRole])

  const onReset = useCallback(() => ListStore.setParams(orderListService, {}), [ListStore, orderListService])
  const onFinish = useCallback(
    data => {
      const [start, end] = data.range || []
      data.startTime = start ? new Date(start).getTime() : undefined
      data.endTime = end ? new Date(end).getTime() : undefined
      delete data.range
      ListStore.setParams(orderListService, data)
    },
    [ListStore, orderListService]
  )
  const EditModal = useCallback(
    (val?, item?) => async () => {
      const done = await AsyncModal({
        content: FormModal,
        params: {
          formEle: EditOrders,
          formProps: {
            values: item
          },
          title: item ? "修改订单" : "添加订单"
        }
      })
      if (done) {
        ListStore.updateList(orderListService)
      }
    },
    []
  )

  const ViewModal = useCallback(
    (val?, item?) => () => {
      const goodsList = Array.isArray(item?.goods) ? item.goods : []
      Modal.info({
        title: "商品信息",
        width: 640,
        content:
          goodsList.length > 0 ? (
            <div style={{ maxHeight: 400, overflowY: "auto" }}>
              {goodsList.map((goods: any, index: number) => {
                const imageUrl = goods?.goodsImage || goods?.goodsImg
                return (
                  <div key={goods?.goodsId ?? index} style={{ padding: "12px 0", borderBottom: "1px solid #f0f0f0" }}>
                    <div>商品名称：{goods?.goodsName || "-"}</div>
                    <div>商品ID：{goods?.goodsId || "-"}</div>
                    <div>申报数量：{goods?.count ?? "-"}</div>
                    <div>申报单位：{goods?.unit || "-"}</div>
                    <div>商品价格：{goods?.price ?? "-"}</div>
                    {imageUrl ? (
                      <div>
                        商品图片：
                        <a href={`${functionCommon.requestHost("public")}${imageUrl}`} target="_blank" rel="noopener noreferrer">
                          查看
                        </a>
                      </div>
                    ) : null}
                  </div>
                )
              })}
            </div>
          ) : (
            <div>暂无商品信息</div>
          )
      })
    },
    []
  )

  const extractFileUrlFromContract = useCallback((contractField?: any): string | undefined => {
    if (!contractField) return undefined
    const candidates = Array.isArray(contractField) ? contractField : [contractField]
    for (const candidate of candidates) {
      if (!candidate) continue
      if (typeof candidate === "object" && typeof candidate.fileUrl === "string") {
        return candidate.fileUrl
      }
      if (typeof candidate === "string") {
        const trimmed = candidate.trim()
        if (!trimmed) continue
        try {
          const parsed = JSON.parse(trimmed)
          if (parsed && typeof parsed.fileUrl === "string") {
            return parsed.fileUrl
          }
        } catch {
          if (trimmed.startsWith("http://") || trimmed.startsWith("https://") || trimmed.startsWith("/")) {
            return trimmed
          }
        }
      }
    }
    return undefined
  }, [])

  const previewContract = useCallback((fileUrl?: string) => {
    if (!fileUrl) {
      Modal.warning({
        title: "提示",
        content: "暂无可预览的合同文件"
      })
      return
    }

    const viewerOrigin = window.location.origin
    const previewBase = `${viewerOrigin}/web/viewer.html?file=`
    const normalizedUrl = functionCommon.requestHost("public") + fileUrl
    const previewUrl = `${previewBase}${encodeURIComponent(normalizedUrl)}`
    window.open(previewUrl, "_blank")
  }, [])

  const renderGoodsName = useCallback((_: string, item: any) => {
    const goodsList = Array.isArray(item?.goods) ? item.goods : []
    if (goodsList.length === 0) {
      return item?.goodsName || "-"
    }
    const names = goodsList.map(entry => entry?.goodsName).filter(Boolean)
    return names.length ? names.join("、") : "-"
  }, [])

  const renderFileUrl = useCallback(
    (_: string, item: any) => {
      const contractUrl = extractFileUrlFromContract(item?.contract)
      const rawUrl = contractUrl || item?.fileUrl
      if (!rawUrl) return "-"

      const extTarget = rawUrl.split("?")[0]?.toLowerCase() || ""
      const isPdf = extTarget.endsWith(".pdf")

      if (isPdf) {
        return (
          <Button type="link" onClick={() => previewContract(rawUrl)}>
            预览
          </Button>
        )
      }

      const downloadUrl = `${functionCommon.requestHost("public")}${rawUrl}`
      return downloadUrl ? (
        <a href={downloadUrl} target="_blank" rel="noopener noreferrer">
          下载
        </a>
      ) : (
        "-"
      )
    },
    [previewContract, extractFileUrlFromContract]
  )

  return (
    <Row>
      <Col span={24}>
        <FormRender
          form={form}
          onReset={onReset}
          onFinish={onFinish}
          layout="inline"
          fieldList={[
            {
              fieldType: "rangeDate",
              formItemConfig: {
                name: "range",
                label: "创建时间"
              },
              config: {
                showTime: !0,
                format: "YYYY-MM-DD HH:mm:ss"
              }
            },
            {
              fieldType: "input",
              formItemConfig: {
                label: "订单编号",
                name: "orderNo"
              },
              config: {
                placeholder: "订单编号"
              }
            },
            {
              fieldType: "input",
              formItemConfig: {
                label: "商品名称",
                name: "goodsName"
              },
              config: {
                placeholder: "商品名称"
              }
            },
            {
              fieldType: "input",
              formItemConfig: {
                label: "客户名称",
                name: "owner"
              },
              config: {
                placeholder: "客户名称"
              }
            },

            Field_Search
          ]}
        />
      </Col>
      <Col span={24}>
        <ListTable
          apiColumns={[
            IndexRender("id", 80),
            ["orderNo", "订单编号"],
            ["goodsName", "商品名称", renderGoodsName],
            ["owner", "客户名称"],
            ["deliveryDate", "交货期"],
            ["fileUrl", "公司合同", renderFileUrl],
            ["updatedBy", "修改人"],
            ["updateTs", "修改时间", DateRender()],
            ["createTs", "创建时间", DateRender()],
            [
              "id",
              "操作",
              OperateRender([
                ["修改", EditModal],
                ["查看", ViewModal]
              ]),
              { width: 80, fixed: "right" }
            ]
          ]}
          apiService={orderListService}
          // testData={orderTestData}
        />
      </Col>
    </Row>
  )
})

export default Page
